package com.yj.provider.dynamicDataSource;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class DataSourceConfig {


    @Bean
    @ConfigurationProperties("spring.datasource.dev")
    public DataSource devDataSource(){

        return DruidDataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties("spring.datasource.prod")
    public DataSource prodDataSource(){
        return DruidDataSourceBuilder.create().build();
    }

    @Bean
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory(MultipleDataSource dataSource)
            throws Exception {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath:com/yj/mapper/**.xml"));
        return sessionFactory.getObject();
    }

    @Bean
    public DataSourceTransactionManager getDataSourceTransactionManager(MultipleDataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }


    /*
        配置动态数据源

     */
    @Bean
    public MultipleDataSource dynamicDataSource(@Qualifier("devDataSource")DataSource devDataSource,@Qualifier("prodDataSource")DataSource prodDataSource){
        //配置切换的动态数据源
        Map<Object,Object> datasourceMap = new HashMap<>();
        datasourceMap.put(DataSourceType.DB_DEV,devDataSource);
        datasourceMap.put(DataSourceType.DB_PROD,prodDataSource);
        MultipleDataSource multipleDataSource = new MultipleDataSource();
        multipleDataSource.setTargetDataSources(datasourceMap);
        // 设置默认数据源
        multipleDataSource.setDefaultTargetDataSource(devDataSource);
        return multipleDataSource;
    }

}
